#include "ringqueue.hpp"
#include "task.hpp"
#include <string.h>
using namespace std;

const char* ops = "+-*/%";

void* consumer(void* args)
{
    ringQueue<Task> *rq = static_cast<ringQueue<Task>* >(args);

    while(1)
    {
        //sleep(1);
        // int data = 0;
        // rq->pop(&data);
        // cout << "consumer done: " << data << endl;

        Task t;
        rq->pop(&t);
        t();
        cout << "consumer done, 处理完成的任务是： " << t.formatRes() << endl;

    }
}

void* productor(void* args)
{
    ringQueue<Task> *rq = static_cast<ringQueue<Task>* >(args);

    while(1)
    {
        // int r = rand()%10;
        // rq->push(r);
        //cout << "productor done: " << r << endl;

        int x = rand() % 100;
        int y = rand() % 100;
        char op = ops[(x + y) % strlen(ops)];
        Task t(x, y, op);
        rq->push(t);
        cout << "productor done, 生产的任务是: " << t.formatArg() << endl;
        sleep(1);
    }
}

int main()
{
    srand(time(0)^pthread_self());
    ringQueue<Task> *rq = new ringQueue<Task>();

    pthread_t c, p;
    //单生产，单消费模式
    pthread_create(&c, nullptr, consumer, rq);
    pthread_create(&p, nullptr, productor, rq);

    pthread_join(c, nullptr);
    pthread_join(p, nullptr);

    delete rq;
    return 0;
}